package com.joker.web.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import com.joker.common.constant.Constants;
import com.joker.common.core.domain.R;
import com.joker.common.core.domain.entity.SysMenu;
import com.joker.common.core.domain.entity.SysUser;
import com.joker.common.core.domain.model.EmailLoginBody;
import com.joker.common.core.domain.model.LoginBody;
import com.joker.common.core.domain.model.LoginUser;
import com.joker.common.core.domain.model.SmsLoginBody;
import com.joker.common.helper.LoginHelper;
import com.joker.orange.domain.InviteCode;
import com.joker.orange.domain.UserInfo;
import com.joker.orange.domain.vo.UserInfoVo;
import com.joker.orange.service.IInviteCodeService;
import com.joker.orange.service.IUserInfoService;
import com.joker.system.domain.vo.RouterVo;
import com.joker.system.service.ISysMenuService;
import com.joker.system.service.ISysUserService;
import com.joker.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.*;

/**
 * 登录验证
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
public class SysLoginController {

    private final SysLoginService loginService;
    private final ISysMenuService menuService;
    private final ISysUserService userService;
    private final IUserInfoService userInfoService;
    private final IInviteCodeService inviteCodeService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public R<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
            loginBody.getUuid(), loginBody.getUserType());
        ajax.put(Constants.TOKEN, token);
//        List<InviteCode> inviteCodeList = generateUniqueRandomCodes(100000);
//        inviteCodeService.insertInviteCode(inviteCodeList);
        return R.ok(ajax);
    }

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int CODE_LENGTH = 8;
    public static List<InviteCode> generateUniqueRandomCodes(int numCodes) {
        List<InviteCode> codes = new ArrayList<>();
        Random random = new Random();

        for (int i = 0; i < numCodes; i++) {
            InviteCode inviteCode = new InviteCode();
            StringBuilder sb = new StringBuilder(CODE_LENGTH);
            // 复制字符集以便每次迭代都能从完整的字符集中选择
            String charactersCopy = new String(CHARACTERS);

            for (int j = 0; j < CODE_LENGTH; j++) {
                int index = random.nextInt(charactersCopy.length());
                char randomChar = charactersCopy.charAt(index);
                sb.append(randomChar);
                // 移除已选择的字符以避免重复
                charactersCopy = charactersCopy.substring(0, index) + charactersCopy.substring(index + 1);
            }
            inviteCode.setInviteCode(sb.toString());
            codes.add(inviteCode);
        }

        return codes;
    }

    /**
     * 退出登录
     */
    @SaIgnore
    @PostMapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public R<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getUserId());
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roles", loginUser.getRolePermission());
        ajax.put("permissions", loginUser.getMenuPermission());
        return R.ok(ajax);
    }

    /**
     * 获取App用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getAppInfo")
    public R<UserInfo> getAppInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        UserInfo user = userInfoService.findUserInfoById(loginUser.getUserId());
        return R.ok(user);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public R<List<RouterVo>> getRouters() {
        Long userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return R.ok(menuService.buildMenus(menus));
    }
}
